using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace Framework.DeepCopy
{
    public static class DeepCopyUtil
    {

        /// <summary>
        /// 可序列化的深度拷贝
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="Obj"></param>
        /// <returns></returns>
        public  static T ReturnNewClass<T>(T Obj)
        {
            if (Obj == null)
                return default(T);
            if (Obj is string || Obj.GetType().IsValueType) return Obj;
            object newObject;
            using( MemoryStream ms=new MemoryStream())
            {
                IFormatter bf = new BinaryFormatter();
                //序列化
                bf.Serialize(ms, Obj);
                //将当前流中得到位置设定成指定值
                ms.Seek(0, SeekOrigin.Begin);
                //反序列化
                newObject = bf.Deserialize(ms);
                ms.Close();
            }
            return (T)newObject;
        }


        /// <summary>
        /// 深拷贝，需要深拷贝的class一定要[Serializable]
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="List">The list.</param>
        /// <returns>List{0}.</returns>
        public static List<T> CloneWithList<T>(object List)
        {
            using (Stream objectStream = new MemoryStream())
            {
                IFormatter formatter = new BinaryFormatter();
                formatter.Serialize(objectStream, List);
                objectStream.Seek(0, SeekOrigin.Begin);
                return formatter.Deserialize(objectStream) as List<T>;
            }
        }
    }
}

